package org.eliza.base.coroutinesx

import kotlinx.coroutines.coroutineScope
import kotlinx.coroutines.delay
import kotlinx.coroutines.launch
import kotlinx.coroutines.runBlocking

private fun basic() = runBlocking { // this: CoroutineScope
//    runBlocking  一个协程构建器 连接{ ... }
    launch {
        //launch是一个协程构建器。它与其余代码同时启动一个新的协程，其余代码继续独立工作
        delay(500L) // non-blocking delay for 1 second (default time unit is ms)
        println("World!") // print after delay
    }
    println("Hello") // main coroutine continues while a previous one is delayed
}

private suspend fun doWorld(name: String) = coroutineScope {  // this: CoroutineScope
    launch {
        delay(500L)
        println("$name :launch")
    }
    println("$name :main")
}

private fun runBlockSingle() {
    // aa main 1
    // aa launch->runBlocking main end->bb :main 1
    // bb launch

    runBlocking {
        doWorld("aa")
    }
    println("runBlocking main end")
    runBlocking {
        doWorld("bb")
    }
    println("runBlocking main end")
}


private fun runBlockMul() {
//   aa :main 1
//   aa launch 2 -> runBlocking doWorld ->bb main 1
//   bb launch 2
    runBlocking {
        doWorld("aa")
        println("runBlocking doWorld")
        doWorld("bb")
    }
}

private fun jobWait(name: String) = runBlocking {
    val job = launch { // launch a new coroutine and keep a reference to its Job
        delay(1000L)
        println("$name launch!")
    }
    println("$name main")
    job.join() // wait until child coroutine completes
    println("jobWait Done")
}

private fun launchLot(name: String) = runBlocking {
    repeat(50_000) { // launch a lot of coroutines
        launch {
            delay(1000L)
            print(".")
        }
    }
}


private fun main() {
//    runBlockSingle()
//    runBlockMul()
//    jobWait("job")
    launchLot("job")
}